package com.chinasofti.zbest.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chinasofti.zbest.common.DateUtil;
import com.chinasofti.zbest.config.AlipayConfig;
import com.chinasofti.zbest.dao.model.Product;
import com.chinasofti.zbest.dao.model.Zborder;
import com.chinasofti.zbest.dao.OrderMapper;
import com.chinasofti.zbest.dao.model.User;
import com.chinasofti.zbest.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinasofti.zbest.web.form.OrderForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author zbest
 * @since 2019-05-28
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Zborder> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 生成订单
     * @param session
     * @param orderForm
     */
    @Override
    public Zborder createOrder(HttpSession session,OrderForm orderForm) {
        User user = (User)session.getAttribute("user");
        Product product = (Product)session.getAttribute("product");
//        Pinyin4jUtil.converterToSpell(user.getUsername()) 取出用户名的全拼
        String orderNumber = DateUtil.format(new Date(),"yyMMddHHmmsss");
        BigDecimal  productPriceStr= orderForm.getProductPrice();
        double productPrice = productPriceStr.doubleValue();
        double subtotalDou = productPrice * orderForm.getProductCount();
        BigDecimal subtotal = new BigDecimal(subtotalDou);
        log.info(subtotal.toString());

        orderForm.setOrderNum(orderNumber);
        orderForm.setSubtotal(subtotal);
        orderForm.setOrderMoney(subtotal);
        orderForm.setOrderStatus("unpaid");
        Zborder order = new Zborder();
        BeanUtils.copyProperties(orderForm,order);
        //订单状态  unpaid:未支付；waitReceiving:待收货；waitEvaluated：待评价；waitShipped:待发货；closed：已关闭
        orderMapper.createOrder(order);

        Zborder zborder = orderMapper.selectById(order.getOrderId());
        return zborder;
    }

    @Override
    public List<Zborder> queryAllOrderById(Integer userId ) {

        List<Zborder> orderList = orderMapper.queryAllOrderById(userId );

        return orderList;
    }

    @Override
    public void modifyStatus(String orderStatus,String orderNum) {

        orderMapper.modifyStatus(orderStatus,orderNum);

    }

    @Override
    public List<Zborder> queryByStatus(Integer userId , String status) {
        List<Zborder> orderList = orderMapper.queryByStatus(userId , status);
        return orderList;
    }

    @Override
    public void ali(HttpServletResponse response, HttpServletRequest request,String orderNum,String orderPay) throws AlipayApiException, IOException {
        //设置编码
        response.setContentType("text/html;charset=utf-8");

        PrintWriter out = response.getWriter();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();
        aliPayRequest.setReturnUrl(AlipayConfig.return_url);
        aliPayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，后台可以写一个工具类生成一个订单号，必填
        String order_number = orderNum;
        //付款金额，从前台获取，必填
        String total_amount = orderPay;
        //订单名称，必填
        String subject = new String("支付宝沙箱支付");
        aliPayRequest.setBizContent("{\"out_trade_no\":\"" + order_number + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(aliPayRequest).getBody();
        //输出
        out.println(result);//以下写自己的订单代码
    }

    @Override
    public Zborder queryByOrderNum(Integer userId , String orderNum) {
        Zborder order = orderMapper.queryByOrderNum(userId , orderNum);
        return order;
    }

    @Override
    public void modifyOrderByOrderStatus(String orderNum , String status) {
        orderMapper.modifyOrderByOrderStatus(orderNum,status);
    }

//    @Override
//    public List<Zborder> queryAllOrderById(Integer orderId) {
//        List<Zborder> zborders = orderMapper.queryAllOrderById(orderId);
//        return zborders;
//    }


}
